package p3.cse;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * This activity runs if the user has entered an appropriate password to decrypt
 * the password database. It enables accessing other activities for managing and
 * viewing accounts.
 * 
 * @see Main
 */
public final class Unlock extends Activity {
	/**
	 * Click event bound to "unlock" button to verify if user entered password
	 * is correct.
	 */
	private OnClickListener checkIfValidPassword = new OnClickListener() {
		public void onClick(final View v) {
			TextView password = (TextView) findViewById(R.id.unlock);

			boolean isCorrectPassword = false;
			Filer filer = Filer.getInstance();

			// Read the user's entered password from from.
			String pwd = password.getText().toString();
			try {
				isCorrectPassword = filer.checkPassword(pwd);
			} catch (IOException e) {
				Log.e("ChangePassword", "Error reading password database", e);
			}

			// Show message or trigger mainunlocked.java activity
			if (!isCorrectPassword) {
				TextView error = (TextView) findViewById(R.id.passworderror);
				error.setTextColor(Color.RED);
				error.setVisibility(1);
			} else {
				// need to initialize filer for other activities
				try {
					filer.init(pwd);
				} catch (IOException e) {
					Log.e("ChangePassword", "Error reading password database",
							e);
				}

				// Trigger the mainunlocked.java activity
				startActivity(new Intent(Unlock.this, Unlocked.class));

				finish();
			}

		}
	};

	/**
	 * Default android constructor called when this activity is created. Binds
	 * the button click event to "Unlock" button.
	 * 
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.unlock);
		Button check = (Button) findViewById(R.id.unlockButton);
		check.setOnClickListener(checkIfValidPassword);
	}
}
